#!/usr/bin/env python

import os
import sys
import re
import wsgiref.handlers

# Google App Engine Imports
from google.appengine.api import mail
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import logging

from model import Code, CodeRevision, Comment, User 
from google.appengine.ext import db

from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter

_DEBUG = True
_ADMIN_EMAIL = "yourabi@enginesnippets.com"
__author__ = "yourabi@enginesnippets.com"
              
class BaseRequestHandler(webapp.RequestHandler):
  """ 
  Base Request Handler 

  Handles rendering templates, and potentially other comment functionality

  """

  def generate(self, template_name, template_values):
    values = {}
    values.update(template_values)

    directory = os.path.dirname(__file__)
    path = os.path.join(directory, 'templates', template_name)
    
    # We check if there is a current user and generate a login or logout URL
    user = users.get_current_user()
    if user:
      log_in_out_url = users.create_logout_url('/')
    else:
      # log_in_out_url = users.create_login_url(self.request.path)
      log_in_out_url = users.create_login_url(self.request.path)

    # We'll display the user name if available and the URL on all pages
    values = {'user': user, 'log_in_out_url': log_in_out_url}
    values.update(template_values)
    
    self.response.out.write(template.render(path, values, debug=_DEBUG))

"""
To keep things unique (URIs) every Code object is accessed via tittle 
under the authors namespace (/yourabi/my-great-title). Titles should (must) be unique within any individuals authors namespace.
"""
class ViewHandler(BaseRequestHandler):
  def get(self, author, title):
    code = Code.gql("WHERE author='%s' and title='%s' order by id" % (author, title)).get()

    self.generate("view.html", template_values={ 
        "author" : author, 
        "title" : title,
        "code" : code,
        
        })

  """
    Handle Adding Comments to Code Snippets
  """
  def post(self):
    pass

"""
Create Snippets

get displays form to upload to code snippet
post handles upload request

"""
class CreateHandler(BaseRequestHandler):
  def get(self):
    self.generate("create.html", template_values={})
  
  """
    The create handler is separate from the update handler
  """
  def post(self):
    title = self.request.get('title')
    code_cont = self.request.get('code')

    # Create base Code object, save to BigTable
    code = Code(title=title,author=users.get_current_user())
    code.put()

    code_revision = CodeRevision(content=code_cont, code=code, version=0)
    code_revision.author = users.get_current_user()
    code_revision.put()
    
    self.response.out.write('Saved Code: %s Title: %s ' % (title,code_cont))

"""
This is where all the love is.
"""
class MainHandler(BaseRequestHandler):
  def get(self):
    q = Code.gql("LIMIT 10")
    results = q.fetch(10)
    self.generate("index.html", template_values={
                                                  "results": results,
                                                })

def UserProfileHandler(BaseRequestHandler):
  def get(self, username):
    pass

# This is where named parameters are created.
_ENGINE_SNIPPETS_URLS = [ 
                          ('/', MainHandler),
                          ('/create', CreateHandler),
                          ('/user/(.*)/(.*)', ViewHandler),
                          ('/user/(.*)', UserProfileHandler),
                        ]

def main():
  application = webapp.WSGIApplication(_ENGINE_SNIPPETS_URLS, debug=_DEBUG)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
